package tp01;

import java.io.IOException;
import javax.comm.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SerialConnectionController extends ConnectionController {

    static CommPortIdentifier portId1;
    static SerialPort serialPort1;
    static Thread readThread;
    private static ServerSocket serverSocket;
    private static Socket socket;
    private String nombrePuerto;

    public SerialConnectionController(String nombrePuerto) {
        this.nombrePuerto = nombrePuerto;
    }

    @Override
    public void conectar() {

        try {

            portId1 = CommPortIdentifier.getPortIdentifier(nombrePuerto);
            serialPort1 = (SerialPort) portId1.open("ComControl", 502);
            ConnectionController.timeStamp = new Date().getTime();
            System.out.println(ConnectionController.timeStamp + ": " + portId1.getName() + " opened for scanner input");
            serialPort1.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort1.setDTR(false);
            serialPort1.setRTS(false);
            ConnectionController.inputStream = serialPort1.getInputStream();
            ConnectionController.outputStream = serialPort1.getOutputStream();

            System.out.println("\u00a1\u00a1Conecci\u00f3n exitosa!!");
        } catch (IOException ex) {
            Logger.getLogger(ConnectionController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedCommOperationException ex) {
            Logger.getLogger(ConnectionController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PortInUseException ex) {
            Logger.getLogger(ConnectionController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPortException ex) {
            Logger.getLogger(ConnectionController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void desconectar() {
        try {
            ConnectionController.inputStream.close();
            ConnectionController.outputStream.close();
            serialPort1.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            Logger.getLogger(ConnectionController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
